#region

using System.Collections.Specialized;
using CommandLineMapper.Helpers;
using CommandLineMapper.Interfaces;

#endregion

namespace CommandLineMapper {
    public class CommandLineParser : ICommandLineParser {
        private readonly ICommandLineSplitter _commandLineSplitter = new CommandLineSplitter();
        private readonly IDoubleQuoteRemover _doubleQuoteRemover = new DoubleQuoteRemover();
        private readonly IObjectMapper _propertyMapper = new ObjectMapper();

        #region Implementation of IProgramParametersParser

        public void Parse(string commandLine, object instance) {
            AssertUtils.AssertArgumentNullForString(commandLine, "commandLine");
            AssertUtils.AssertArgumentNull(instance, "instance");
            NameValueCollection parameters = _commandLineSplitter.Split(commandLine);
            if(parameters.Count == 0) {
                return;
            }
            RemoveDoubleQuotes(parameters);
            _propertyMapper.Map(instance, parameters);
        }

        #endregion

        private void RemoveDoubleQuotes(NameValueCollection collection) {
            foreach (string key in collection.AllKeys) {
                collection[key] = _doubleQuoteRemover.Remove(collection[key]);
            }
        }
    }
}